#include "socket.h"

Socket::Socket(void):m_fd(-1)
{
}
Socket::~Socket(void)
{
}
int Socket::Recv(void* buf, int len)
{
	if( -1 == m_fd || NULL == buf || len < 1 )
	{
		return -1;
	}
	return recv(m_fd, buf, len, 0);
}
int Socket::Send(const void* data, int len)
{
	if( -1 == m_fd || NULL == data || len < 1 )
	{
		return -1;
	}
	return send(m_fd, data, len, 0);
}
int Socket::RecvOob(void* buf, int len)
{
	if( -1 == m_fd || NULL == buf || len < 1 )
	{
		return -1;
	}
	return recv(m_fd, buf, len, MSG_OOB);
}
int Socket::SendOob(const void* data, int len)
{
	if( -1 == m_fd || NULL == data || len < 1 )
	{
		return -1;
	}
	return send(m_fd, data, len, MSG_OOB);
}
bool Socket::Block(void)
{
	int flag = fcntl(m_fd, F_GETFL, 0);

	int ret = fcntl(m_fd, F_SETFL, flag & ~O_NONBLOCK);

	return (0 == ret);
}
bool Socket::Unblock(void)
{
	int flag = fcntl(m_fd, F_GETFL, 0);

	int ret = fcntl(m_fd, F_SETFL, flag | O_NONBLOCK);

	return (0 == ret);
}
int Socket::GetSocket(void)
{
	return m_fd;
}
void Socket::SetSocket(int fd)
{
	m_fd = fd;
}
bool Socket::ReuseAddress(bool b)
{
	int reuse = b ? 1 : 0;

	int ret = setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, (socklen_t)sizeof(reuse));

	return (0 == ret);
}
bool Socket::Close(void)
{
	if( -1 == m_fd )
	{
		close(m_fd);
		m_fd = -1;
	}
	return (-1 == m_fd);
}
